package com.xsjl.article.service;

import com.xsjl.article.mapper.CommentRepository;
import com.xsjl.article.pojo.Comment;
import com.xsjl.common.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CommentService {
    @Autowired    
    private CommentRepository commentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    public void add(Comment comment){
        IdWorker idWorker = new IdWorker();
        comment.setId(idWorker.nextId()+""  );
        comment.setZan(0);
        comment.setParentid("0");
        comment.setPublishdate(new Date());
        commentRepository.save(comment);                
    }

    public List<Comment> findByArticleid(String articleid){
        return commentRepository.findByArticleidOrderByZanDesc(articleid);
    }

    public void remove(String id) {
        commentRepository.deleteById(id);
    }


    public void addThumbup(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("zan", 1);
        mongoTemplate.updateFirst(query, update, "comments");
    }

}
